﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ART.Windows.HelpDesk.TicketServerCore
{
    public class TicketCore
    {
        private ManualResetEvent m_objStopEvent;
        private Thread m_objTicketCoreThread;
        private bool m_bIsTicketCoreRunning = false;

        private void TickCoreThread()
        {
            if (m_bIsTicketCoreRunning) return;
            m_bIsTicketCoreRunning = true;

            #region check  noi dung mail
            while (!m_objStopEvent.WaitOne(0, true))
            {
                try
                {
                    new btnet.EngineMail().ProcessMails();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                Thread.Sleep(300000); // 300*1000 = 300 seconds = 5 minutes
            }
            
            #endregion

        }

        public void Start()
        {
            if (m_bIsTicketCoreRunning) return;
            m_objStopEvent = new ManualResetEvent(false);
            m_objTicketCoreThread = new Thread(new ThreadStart(TickCoreThread));
            m_objTicketCoreThread.Start();

        }

        public void Stop()
        {
            if (!m_bIsTicketCoreRunning) return;
            m_objStopEvent.Set();
            m_objTicketCoreThread.Join(50000);
            if (m_bIsTicketCoreRunning) m_objTicketCoreThread.Abort();
            m_bIsTicketCoreRunning = false;
        }
    }
}
